package com.example.demo.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.mapper.UserInfoMapper;
import com.example.demo.service.UserInfoService;
import com.example.demo.vo.UserInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserInfoServiceImpl implements UserInfoService {
    @Resource
    private UserInfoMapper userInfoMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Value("${jwt.secret}")
    private String secret;
    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Override
    public Boolean register(Map map) {

        String username = Convert.toStr(map.get("username"));
        String password = Convert.toStr(map.get("password"));
        String email = Convert.toStr(map.get("email"));
        String names = Convert.toStr(map.get("names"));
        String tel = Convert.toStr(map.get("tel"));
        String gender = map.get("gender") == "male" ? "男" : "女";
        Date birthDay = Convert.toDate(map.get("birthday"));

        //注册就是将用户名和密码保存到数据库中
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        Integer integer = userInfoMapper.selectCount(queryWrapper);
        if (integer > 0) {
            return false;
        }
        //将密码进行加密处理
        String s = DigestUtil.md5Hex(password);
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(username);
        userInfo.setPassWord(s);
        userInfo.setBirthDay(birthDay);
        userInfo.setName(names);
        userInfo.setTel(tel);
        userInfo.setGender(gender);
        userInfo.setEmail(email);
        userInfo.setRoleId("4");

        return userInfoMapper.insert(userInfo) > 0;
    }

    @Override
    public String login(String username, String password) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        String s = DigestUtil.md5Hex(password);
        queryWrapper.eq("username", username).eq("password", s);
        UserInfo userInfo = this.userInfoMapper.selectOne(queryWrapper);
        if (ObjectUtil.isEmpty(userInfo)) {
            return null;
        }

        HashMap<String, Object> claims = new HashMap<>();
        claims.put("username", username);
        //生成token
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS256, secret)
                .setExpiration(DateUtil.offset(new Date(), DateField.HOUR, 12))
                .compact();

        return token;
    }

    @Override
    public UserInfo queryUserByToken(String token) {
        try {
            Claims body = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();

            String username = Convert.toStr(body.get("username"));

            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", username);
            return this.userInfoMapper.selectOne(queryWrapper);

        } catch (ExpiredJwtException e) {
            log.info("token已经过期！token=" + token);
        } catch (Exception e) {
            log.error("token不合法！token=" + token, e);
        }
        return null;
    }
}
